<!-- 打卡 -->
<template>
  <ContainerLayout class="clockin-container">
    <div class="clockin-container-content">
      <template v-if="dataList">
        <el-calendar v-model="calendarValue" class="calendar-warp">
          <template #date-cell="{ data }">
            <CalendarCell :date="data.date" :legal-list="legalList" :clockinInfo="clockinInfo(data.date)" @cellClick="handleClickBtnOpenDialog" @cellDelete="handlerClickBtnDelete" />
          </template>
        </el-calendar>
      </template>
    </div>
  </ContainerLayout>
  <DialogClockIn ref="dialogClockInRef" :clockinCategoryList="clockinCategoryList" @submit-successed="handleDialogSubmitSuccessed" />
</template>
<script lang="ts" setup>
import ContainerLayout from '../layout/ContainerLayout.vue'
import DialogClockIn from '../components/dialog/DialogClockIn.vue'
import { ref, onMounted, watch } from 'vue'
import { useUsersStore, useClockinCategoryStore, useLegalStore } from '../stores'
import http from '../http'
import { formatDate } from '../utils'
import { ElMessageBox } from 'element-plus'
import CalendarCell from '../components/Clockin/CalendarCell.vue'

const calendarValue = ref(new Date())
const dialogClockInRef = ref()
const clockinCategoryList = ref<{ dictValue: number; dictLabel: string }[]>(useClockinCategoryStore().getAll())
const dataList = ref<any>()
const resultList = ref<any[]>([])
const legalList = ref<any[]>([])

watch(
  () => calendarValue.value,
  async () => {
    await initData()
  }
)

const isToday = (date: Date) => {
  // 获取当前日期
  const today = new Date()
  // 将当前日期的时间部分置为 0
  today.setHours(0, 0, 0, 0)

  // 处理传入的日期参数
  const inputDate = new Date(date)
  // 将传入日期的时间部分置为 0
  inputDate.setHours(0, 0, 0, 0)

  // 比较两个日期是否相等
  return inputDate.getTime() === today.getTime()
}

/**
 * 点击按钮打开对话框
 *
 * @param date 日期对象
 */
const handleClickBtnOpenDialog = (val: { date: Date; clockinCategory: string }) => {
  const _checkIsClockIn = checkIsClockIn(val.date)
  if (_checkIsClockIn >= 2) {
    return ElMessageBox.alert('您已打卡，不可重复打卡', '提示')
  }
  if (dialogClockInRef.value) {
    // date
    dialogClockInRef.value.openDialog({
      date: val.date,
      clockinCategoryList: clockinCategoryList.value,
      defaultClockinCategory: val.clockinCategory,
      isComp: !isToday(val.date),
      checkIsClockIn: _checkIsClockIn,
    })
  }
}

/**
 * 获取考勤列表
 *
 * @returns {Promise<void>}
 */
const getClockinCategoryList = async () => {
  const currentUser = useUsersStore().getAllState()

  const year = calendarValue.value.getFullYear()
  const month = calendarValue.value.getMonth()
  const start = new Date(year, month, 1)
  const end = new Date(year, month + 1, 0)
  const params = {
    userName: currentUser.username,
    pageSize: 99999,
    startClockinDate: formatDate(start, 'yyyy-MM-dd'),
    endClockinDate: formatDate(end, 'yyyy-MM-dd'),
  }
  const { rows } = await http({
    method: 'GET',
    path: '/dev-api/oa/clockin/list',
    params,
  })
  const result: any = {}
  rows.forEach((row: any) => {
    const key = `${row.clockinDate}-${row.clockinCategory}`
    result[key] = {
      ...row,
      loginTime: row.clockinTime.split(' ')[1],
    }
  })
  dataList.value = result
  resultList.value = rows
}

/**
 * 根据日期和类别类型显示打卡信息
 *
 * @param date 日期对象
 * @param categoryType 类别类型，数字类型
 * @returns 打卡时间，如果没有找到则返回空字符串
 */
const showClockinInfoByDate = (date: Date, categoryType: number) => {
  const logDate = formatDate(date, 'yyyy-MM-dd')
  if (dataList.value) {
    const result = dataList.value[`${logDate}-${categoryType}`]
    if (result) {
      return result?.loginTime || ''
    } else {
      return ''
    }
  }
}

/**
 * 根据给定日期获取上下班打卡信息
 *
 * @param date 日期对象
 * @returns 包含上午和下午打卡信息的对象
 */
const clockinInfo = (date: Date) => {
  const mornin = showClockinInfoByDate(date, 0)
  const evening = showClockinInfoByDate(date, 1)
  return {
    mornin,
    evening,
  }
}

/**
 * 处理点击删除按钮的事件
 *
 * @param date 删除记录对应的日期
 */
const handlerClickBtnDelete = async (date: Date) => {
  const ids: any[] = []
  resultList.value.map((e: any) => {
    if (e.clockinDate === formatDate(date, 'yyyy-MM-dd')) {
      ids.push(e.id)
    }
  })
  ElMessageBox.confirm('确定删除?', '提示')
    .then(async () => {
      const res = await http({
        method: 'DELETE',
        path: `/dev-api/oa/clockin/${ids.join(',')}`,
        params: {},
      })
      console.log('res', res)
    })
    .catch(() => {
      // catch error
    })
}
/**
 * 检查 日期是否已经打卡
 *
 * @param date 删除记录对应的日期
 */
const checkIsClockIn = (date: Date) => {
  const { mornin, evening } = clockinInfo(date)
  if (mornin !== '' && evening !== '') {
    return 2
  } else if (mornin == '' && evening == '') {
    return -1
  } else if (mornin == '') {
    return 0
  } else if (evening == '') {
    return 1
  } else {
    return 3
  }
}

/**
 * 处理对话框提交成功的回调函数
 *
 * @async
 */
const handleDialogSubmitSuccessed = async () => {
  await getClockinCategoryList()
}

/**
 * 初始化数据函数
 *
 * 异步函数，用于初始化数据。
 * 首先，通过调用 getClockinCategoryList 函数获取考勤分类列表。
 * 然后，通过 useLegalStore 获取所有状态，并筛选出年份为当前年份的条目，赋值给 legalList.value。
 */
const initData = async () => {
  await getClockinCategoryList()
  legalList.value = useLegalStore()
    .getAllState()
    .filter((item) => item.yearNum === new Date().getFullYear())
}
onMounted(async () => {
  await initData()
})
</script>

<style lang="scss" scoped>
.clockin-container {
  display: flex;
  flex-direction: row;
  .clockin-container-content {
    height: 100%;
    flex: 1;
    .calendar-warp {
      height: 100%;
    }
  }
}
</style>

<style lang="scss">
.calendar-warp {
  display: flex;
  flex-direction: column;
  .el-calendar__body {
    flex: 1;
    padding-bottom: 10px;
    .el-calendar-day {
      height: 100%;
    }
    .el-calendar-table {
      height: 100%;
    }
  }
}
</style>
